package com.t.bricks.bussiness.service.flowwork.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.t.bricks.bussiness.db.dao.flowwork.FlowWorkDao;
import com.t.bricks.bussiness.db.entity.flowwork.FlowDefine;
import com.t.bricks.bussiness.db.entity.flowwork.FlowWork;
import com.t.bricks.bussiness.service.flowwork.FlowWorkService;
import com.t.bricks.model.MsgEmity;
import com.t.bricks.utils.function.data.UUIDUtil;
import com.t.bricks.utils.spring.ModuleUtil;

/**
 * 流程实例'FlowWork表'基本业务操作类接口实现
 */
@Service
public class FlowWorkServiceImpl implements FlowWorkService<FlowWork> {

	@Autowired
	private FlowWorkDao<FlowWork> flowWorkDao;

	/**
	 * 指定流程发起工作流
	 * @param sDefineSign 所用流程标识
	 * @param sInitiateDescription 发起节点的描述
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity addWork(String sDefineSign, String sInitiateDescription) {
		if (null == sDefineSign || "".equals(sDefineSign.trim())) {
			return MsgEmity.err(8001, "未指定流程编号");
		}
		
		if (null == sInitiateDescription || "".equals(sInitiateDescription.trim())) {
			return MsgEmity.err(8002, "发起节点的描述");
		}
		
		MsgEmity me = this.callMapping("findBysSign", sDefineSign.trim());
		if (!me.isSuccess()) {
			return MsgEmity.err(8003, "未能查询到对应的流程定义信息");
		}
		
		FlowDefine flowDefine = me.getData();
		
		Date date = new Date();
		FlowWork flowWork = new FlowWork();
		flowWork.setuId(UUIDUtil.get());
		flowWork.setsDefineSign(flowDefine.getsSign());
		flowWork.setsDescription(flowDefine.getsDescription());
		flowWork.setsSuccessApi(flowDefine.getsSuccessApi());
		flowWork.setsCreatorId(ModuleUtil.currentLoginUserId());//发起者编号
		flowWork.setsCreatorName(ModuleUtil.currentLoginUserName());
		flowWork.setsMemo(flowDefine.getsMemo());
		flowWork.setsCreator(ModuleUtil.currentLoginUserId());
		flowWork.setdCreateDate(date);
		flowWork.setsModifieder(ModuleUtil.currentLoginUserId());
		flowWork.setdModifiedDate(date);
		flowWork.setiState(1);//状态(枚举,1:进行中;2:失败;3:作废;4:成功)
		flowWork.setiIndex(1);
		flowWork.setiVersion(1);
		
		return flowWorkDao.createWork(flowWork, sInitiateDescription);
	}

	/**
	 * 删除
	 * @param iVersion 数据版本号
	 * @param uId 记录编号
	 * @param onlyCreator 仅允许创建者操作
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity del(Integer iVersion, String uId) {
		MsgEmity me = this.del(iVersion, uId, true);
		if (!me.isSuccess()) {
			return me;
		}
		
		return me;
	}
	
	/**
	 * 修改状态
	 * @param uId 编号
	 * @param iState 状态值
	 * @param iVersion 记录版本号
	 * @param sMemo 备注
	 * @return MsgEmity 返回执行情况
	 */
	@Override
	public MsgEmity changeState(String uId, Integer iState, Integer iVersion,
			String sMemo) {
		MsgEmity me = this.changeSetp(uId, iState, iVersion, sMemo, false);//是否单向 设置为单向则新值必须大于旧值才能执行
		if (!me.isSuccess()) {
			return me;
		}
		
		return me;
	}

}
